package com.ac.util;

import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import com.ac.model.Page;

import lombok.AllArgsConstructor;

@Component
@AllArgsConstructor
public class MongoUtil {

	static MongoUtil manger;

	final MongoTemplate mongo;

	@PostConstruct
	public void init() {
		manger = this;
	}

	/**
	 * 根据条件进行分页查询-使用默认排序和查询条件
	 * 
	 * @param <T>
	 * @param base
	 * @param entityClass
	 * @return
	 */
	public static <T> Page findPge(Page base, Class<T> entityClass) {
		return findPge(base, entityClass, null, null);
	}

	/**
	 * 根据条件进行分页查询-使用默认排序
	 * 
	 * @param <T>
	 * @param base
	 * @param entityClass
	 * @param ct
	 * @return
	 */
	public static <T> Page findPge(Page base, Class<T> entityClass, Criteria ct) {
		return findPge(base, entityClass, ct, null);
	}

	/**
	 * 根据条件进行分页查询
	 * 
	 * @param <T>
	 * @param base
	 * @param entityClass
	 * @param ct
	 * @param by
	 * @return
	 */
	public static <T> Page findPge(Page base, Class<T> entityClass, Criteria ct, Sort by) {

		if (by == null)
			by = Sort.by(Sort.Order.asc("createTime"));
		if (ct == null)
			ct = new Criteria();

		Query query = new Query(ct).skip((base.getPageNum() - 1) * base.getPageSize()).limit(base.getPageSize());

		query.with(by);

		long count = manger.mongo.count(new Query(ct), entityClass);
		List<T> list = manger.mongo.find(query, entityClass);

		Page page = new Page();
		page.setList(list);
		page.setTotal(count);
		return page;
	}

}
